package com.tx.AI;

import cn.hutool.core.collection.CollUtil;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;

import java.util.List;
import java.util.Objects;

public class WeberTest {

    private static WebDriver driver = null;

    public static void init() throws InterruptedException {
        // 设置ChromeDriver的路径
        System.setProperty("webdriver.chrome.driver", "C:\\Users\\Join\\Desktop\\tong-xia-club\\tong-xia-club\\tx-service\\tx-service-admin\\src\\main\\java\\com\\tx\\AI\\chromedriver.exe");
        ChromeOptions options = new ChromeOptions();
        // 启用无头模式
        options.addArguments("--headless");
        // 设置浏览器窗口大小为 1080 像素宽度（可以根据需要调整）
        options.addArguments("window-size=1920x1080");
        // 初始化ChromeDriver
        driver = new ChromeDriver(options);

        // 打开百度网站
        driver.get("https://chat18.aichatosai.com/#/chat/1756195993125");

        // 输出网页标题
        while (CollUtil.isEmpty(driver.findElements(By.className("n-input__textarea-el")))){
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        Thread.sleep(1000);
    }


    public static String getAnser(String question)  {
        if (Objects.isNull(driver)){
            try {
                init();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }

        List<WebElement> elements = driver.findElements(By.className("n-input__textarea-el"));
        elements.get(0).sendKeys(question, Keys.ENTER); //n-button__content
//        Thread.sleep(1000);
//        System.out.println("1111111");
//        System.out.println(driver.getPageSource());
//        Thread.sleep(1000);
//        System.out.println("222");
//        System.out.println(driver.getPageSource());
        while (isRunningButton(driver)){
            System.out.println("还在等待中");
        }
        List<WebElement> elements1 = driver.findElements(By.className("markdown-body"));
        String targetText = elements1.get(elements1.size()-1).getText();
        System.out.println(targetText);
        // 关闭浏览器
        return targetText;
    }

    public static void  destory(){
        driver.quit();
    }

    private static boolean isRunningButton(WebDriver driver) {

        List<WebElement> elements = driver.findElements(By.tagName("span"));
        try {
            for (WebElement element : elements) {
                if (element.getText().contains("Stop")){
                    return true;
                }
            }
        }catch (Exception e){
            return true;
        }
        return false;
    }
}
